<template>
  <div class="product-management">
    <div class="page-header">
      <h2>商品管理</h2>
      <el-button type="primary" @click="showAddDialog = true">添加商品</el-button>
    </div>

    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索商品名称或编码"
        style="width: 300px"
        clearable
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <el-table :data="filteredProducts" style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="productCode" label="商品编码" width="120" />
      <el-table-column prop="name" label="商品名称" width="200" />
      <el-table-column prop="description" label="描述" width="250" />
      <el-table-column prop="price" label="价格" width="100">
        <template #default="scope">
          ¥{{ scope.row.price.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" width="100" />
      <el-table-column prop="category" label="分类" width="120" />
      <el-table-column prop="unit" label="单位" width="80" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="editProduct(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteProduct(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑商品对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingProduct ? '编辑商品' : '添加商品'"
      width="600px"
    >
      <el-form :model="productForm" :rules="rules" ref="productFormRef" label-width="100px">
        <el-form-item label="商品编码" prop="productCode">
          <el-input v-model="productForm.productCode" />
        </el-form-item>
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="productForm.name" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="productForm.description" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="productForm.price" :precision="2" :min="0" />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model="productForm.stock" :min="0" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-input v-model="productForm.category" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="productForm.unit" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="saveProduct">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

export default {
  name: 'ProductManagement',
  components: {
    Search
  },
  setup() {
    const loading = ref(false)
    const products = ref([])
    const filteredProducts = ref([])
    const searchQuery = ref('')
    const showAddDialog = ref(false)
    const editingProduct = ref(null)
    const productFormRef = ref()

    const productForm = reactive({
      productCode: '',
      name: '',
      description: '',
      price: 0,
      stock: 0,
      category: '',
      unit: ''
    })

    const rules = {
      productCode: [{ required: true, message: '请输入商品编码', trigger: 'blur' }],
      name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
      price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
      stock: [{ required: true, message: '请输入库存', trigger: 'blur' }]
    }

    const loadProducts = async () => {
      loading.value = true
      try {
        const response = await fetch('/api/products')
        const data = await response.json()
        products.value = data
        filteredProducts.value = data
      } catch (error) {
        ElMessage.error('加载商品数据失败')
        // 使用模拟数据
        products.value = [
          {
            id: 1,
            name: '可口可乐',
            price: 3.50,
            stock: 100,
            category: '饮料',
            description: '330ml 可口可乐'
          },
          {
            id: 2,
            name: '康师傅方便面',
            price: 4.50,
            stock: 50,
            category: '食品',
            description: '红烧牛肉面 108g'
          }
        ]
        filteredProducts.value = products.value
      } finally {
        loading.value = false
      }
    }

    const handleSearch = () => {
      if (!searchQuery.value) {
        filteredProducts.value = products.value
      } else {
        filteredProducts.value = products.value.filter(product =>
          product.name.includes(searchQuery.value) ||
          product.productCode.includes(searchQuery.value)
        )
      }
    }

    const editProduct = (product) => {
      editingProduct.value = product
      Object.assign(productForm, product)
      showAddDialog.value = true
    }

    const saveProduct = async () => {
      try {
        const url = editingProduct.value ? `/api/products/${editingProduct.value.id}` : '/api/products'
        const method = editingProduct.value ? 'PUT' : 'POST'
        
        const response = await fetch(url, {
          method,
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(productForm)
        })

        if (response.ok) {
          ElMessage.success(editingProduct.value ? '商品更新成功' : '商品添加成功')
          showAddDialog.value = false
          loadProducts()
          resetForm()
        }
      } catch (error) {
        ElMessage.error('操作失败')
        // 模拟成功操作
        ElMessage.success(editingProduct.value ? '商品更新成功' : '商品添加成功')
        showAddDialog.value = false
        loadProducts()
        resetForm()
      }
    }

    const deleteProduct = async (id) => {
      try {
        await ElMessageBox.confirm('确定要删除这个商品吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        const response = await fetch(`/api/products/${id}`, { method: 'DELETE' })
        if (response.ok) {
          ElMessage.success('删除成功')
          loadProducts()
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
          // 模拟成功删除
          ElMessage.success('删除成功')
          loadProducts()
        }
      }
    }

    const resetForm = () => {
      editingProduct.value = null
      Object.assign(productForm, {
        productCode: '',
        name: '',
        description: '',
        price: 0,
        stock: 0,
        category: '',
        unit: ''
      })
    }

    onMounted(() => {
      loadProducts()
    })

    onUnmounted(() => {
      // 清理组件状态
      loading.value = false
      showAddDialog.value = false
      editingProduct.value = null
    })

    return {
      loading,
      products,
      filteredProducts,
      searchQuery,
      showAddDialog,
      editingProduct,
      productForm,
      productFormRef,
      rules,
      handleSearch,
      editProduct,
      saveProduct,
      deleteProduct
    }
  }
}
</script>

<style scoped>
.product-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 